package jp.ddo.trismegistos.action.impl;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jp.ddo.trismegistos.action.Action;
import jp.ddo.trismegistos.bean.ErrorInfo;

/**
 * Actionの抽象クラス。
 * 
 * @author y_sugasawa
 * @since 2011/06/04
 * 
 */
public abstract class AbstractAction implements Action {

	/** リクエスト情報 */
	private HttpServletRequest request;

	/** セッション情報 */
	private HttpSession session;

	/** アプリケーション情報 */
	private ServletContext application;

	/** エラーメッセージ格納クラス */
	private ErrorInfo errors;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setHttpServletRequest(final HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setHttpSession(final HttpSession session) {
		this.session = session;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setServletContext(final ServletContext application) {
		this.application = application;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getEscapedParameter(final String key) {
		final String ret = request.getParameter(key);
		if (ret == null) {
			return ret;
		}
		return ret.replaceAll("<", "&lt;").replaceAll(">", "&gt;")
				.replaceAll("&", "&amp;").replaceAll("\"", "&quot:")
				.replaceAll("\n", "<br>");
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getParameter(final String key) {
		return request.getParameter(key);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String[] getParameters(final String key) {
		return request.getParameterValues(key);
	}

	/**
	 * {@inheritDoc}
	 */
	public Object getRequest(final String key) {
		return request.getAttribute(key);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getSession(final String key) {
		return session.getAttribute(key);
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeSession(final String key) {
		session.removeAttribute(key);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getApplication(final String key) {
		return application.getAttribute(key);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setRequest(final String key, final Object obj) {
		request.setAttribute(key, obj);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setSession(final String key, final Object obj) {
		session.setAttribute(key, obj);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setApplication(final String key, final Object obj) {
		application.setAttribute(key, obj);
	}

	/**
	 * {@inheritDoc}
	 */
	public void validate() {
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean check() {
		request.setAttribute("errors", errors);
		return errors == null;
	}

	/**
	 * @return the errors
	 */
	public ErrorInfo getErrors() {
		return errors;
	}

	/**
	 * エラーメッセージを追加する。
	 * 
	 * @param message
	 *            エラーメッセージ
	 */
	public void addErrors(final String message) {
		if (errors == null) {
			errors = new ErrorInfo();
		}

		errors.addError(message);
	}
}
